-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Add scala.compiletime.requireConst #9764
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add scala.compiletime.requireConst #9764
Conversation
This is an ability we lost when we fixed the semantics of inline parameters. Currently, we can only do these checks using macros. |
This comment has been minimized.
This comment has been minimized.
I find it weird that the same syntax is used in if as a condition and as an assertion. I think the assertion should be more explicit, like |
There is only one method, that happens to be used in both use cases. If I rename it we would end up with if requireConst(n == 0) then 1L
else if requireConst(n % 2 == 1) then x * power(x, n - 1) which is a bit too long. |
I think that The fact that it's bit longer should not stand in the way of clarity. |
c765092
to
68c2487
Compare
Ok. I changed |
I still find it weird that the same method call does something different (return a value or emitting an error) depending on where it's used syntactically. I don't think we've ever had something like that in Scala. |
That's not what's happening here. In both cases it a) emits an error if the argument is not constant, and b) returns the constant value of the argument if it is constant. In the first example, the returned value is just discarded. |
Ah I see, I misread |
The doc should explicitly state that the value is returned. |
Alternative names
These names seem to indicate that the value is returned |
90fbfdb
to
01bc23d
Compare
`requireConst` checks at compiletime that the provided values is a constant after inlining and constant folding. Usage: ```scala inline def twice(inline n: Int): Int = requireConst(n) // static assertion that the parameter `n` is a constant n + n twice(1) val m: Int = ... twice(m) // error: expected a constant value but found: m ```
01bc23d
to
107c36b
Compare
@liufengyun I updated this PR to match what we agreed during the meeting. Now inline def requireConst(inline x: Boolean | Byte | Short | Int | Long | Float | Double | Char | String): Unit = () |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
Side note: I find this is a very good practice to express pre-conditions in meta-programming.
I can foresee similar APIs will be helpful in macros as well. It helps simplify error handling code and makes the assumptions clear.
Co-authored-by: Fengyun Liu <[email protected]>
requireConst
checks at compiletime that the provided values is a constant after inlining and constant folding.Usage: